"ui";
var color = "#009688";
var menuWidth = 180;
var floatyWindow=false;
radioMainMap = {1:"1分钟",3:"3分钟",5:"5分钟"};
radioOtherMap = {30:"30秒",45:"45秒",60:"60秒"};


var utils = require("./js/utils");

//加载远端配置APP信息
var apps = [];
threads.start(function(){
    utils.createFile("https://code.aliyun.com/zousy201314/xinnyJs/raw/master/js/apps.js",files.cwd() + "/js/");
    var appMap = require("./js/apps");
    for(id in appMap){
        apps.push({id:id,name:appMap[id].appName});
    }
});
ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="xinnyJs工具箱"/>
                <tabs id="tabs"/>
            </appbar>
            <viewpager id="viewpager">
                <frame>
                <vertical align="center" padding="0 10" margin="0">
                        <linear padding="5">
                            <text textStyle="bold" size="15"  w="auto" h="*" gravity="center">主宝贝浏览分钟：</text>
                            <radiogroup id='mainMins' orientation="horizontal">
                                <radio text='{{radioMainMap[1]}}'></radio>
                                <radio text='{{radioMainMap[2]}}'></radio>
                                <radio text='{{radioMainMap[3]}}' checked="true"></radio>
                            </radiogroup>
                        </linear>
                        <linear padding="5">
                            <text textStyle="bold" size="15" h="*" gravity="center">货比浏览时长（秒）：</text>
                            <radiogroup id='otherSecs' orientation="horizontal">
                                <radio text='{{radioOtherMap[30]}}' checked="true"></radio>
                                <radio text='{{radioOtherMap[45]}}'></radio>
                                <radio text='{{radioOtherMap[60]}}'></radio>
                            </radiogroup>
                        </linear>
                        <linear padding="5">
                            <text textStyle="bold" size="15" h="*" gravity="center">货比宝贝数量：</text>
                            <radiogroup id='otherSize' orientation="horizontal">
                                <radio text='3' checked="true"></radio>
                                <radio text='4'></radio>
                                <radio text='5'></radio>
                            </radiogroup>
                        </linear>

                        <button id="taobao" text="自动浏览" style="Widget.AppCompat.Button.Colored" w="auto" layout_gravity="center"  gravity="center" textSize="20" marginTop="0"/>
                    </vertical>
                </frame>
                <frame>
                <vertical align="center" padding="0 10" margin="0">
                    <grid id="apps" spanCount="2" h="auto">
                        <checkbox id="{{this.id}}" text="{{this.name}}" checked="{{this.checked}}" />
                    </grid>
                    
                    <button id="watch" text="运行" style="Widget.AppCompat.Button.Colored" w="auto" layout_gravity="center"  gravity="center" textSize="20" marginTop="0"/>
                </vertical>
                </frame>
                <frame>
                    <text text="待开发。。。" textColor="green" textSize="16sp"/>
                </frame>
            </viewpager>
        </vertical>
        <vertical layout_gravity="left" bg="#ffffff" w="{{menuWidth}}" h="auto">
            <img w="{{menuWidth}}" h="20" scaleType="fitXY" src="#009688"/>
            <Switch id="autoService" text="无障碍服务" gravity="center" checked="{{auto.service != null}}" padding="5" textSize="15sp"/>
            <Switch id="floatyWindow" text="悬浮框" gravity="center" checked="{{floatyWindow}}" padding="5" textSize="15sp"/>
            <list id="menu">
                <horizontal bg="?selectableItemBackground" w="*">
                    <img w="50" h="50" padding="16" src="{{this.icon}}" tint="{{color}}"/>
                    <text textColor="black" textSize="15sp" text="{{this.title}}" layout_gravity="center"/>
                </horizontal>
            </list>
        </vertical>
    </drawer>
);
 

//无障碍服务开关
ui.autoService.on("check", function(checked) {
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    } else if (auto.service == null) {
        if (checked) {
            engines.execScript("Auto", "auto.waitFor();\console.log('无障碍权限已开启！')");
        }
    }
});
// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function () {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
});
//悬浮窗开关
ui.floatyWindow.on("check", function(checked) {
    floatyWindow=checked;
});
 
//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu=>{
    menu.add("设置");
    menu.add("关于");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item)=>{
    switch(item.getTitle()){
        case "设置":
            toast("还没有设置");
            break;
        case "关于":
            alert("关于", "暂无");
            break;
    }
    e.consumed = true;
});
activity.setSupportActionBar(ui.toolbar);
 
//设置滑动页面的标题
ui.viewpager.setTitles(["淘宝自动浏览", "小视频", "鱼塘"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);


ui.viewpager.setOnPageChangeListener({
    //已选定页面发生改变时触发
    onPageSelected: function (index) {
       if(index == 1){
        ui.apps.setDataSource(apps);
        ui.apps.on("item_click", function(app,index){
            apps[index].checked = !apps[index].checked;
        });
       }
        
    }
})
 
//让工具栏左上角可以打开侧拉菜单
ui.toolbar.setupWithDrawer(ui.drawer);
 
ui.menu.setDataSource([
//   {
//       title: "选项一",
//       icon: "@drawable/ic_android_black_48dp"
//   },
//   {
//       title: "选项二",
//       icon: "@drawable/ic_settings_black_48dp"
//   },
//   {
//       title: "选项三",
//       icon: "@drawable/ic_favorite_black_48dp"
//   },
  {
      title: "退出",
      icon: "@drawable/ic_exit_to_app_black_48dp"
  }
]);
 
ui.menu.on("item_click", item => {
    switch(item.title){
        case "退出":
            engines.stopAllAndToast();
            ui.finish();
            break;
    }
});
function findKeyByValue(obj,value){
    if(!obj){return value;}
    for(var key in obj){
        if(value == obj[key]){
            return key;
        }
    }
    return "";
}

function radioVal(radioGroup,map){
    var count=radioGroup.getChildCount();
    for(var i = 0;i< count;i++){
        var radio = radioGroup.getChildAt(i);
        if(radio.checked){
            return findKeyByValue(map,radio.getText());
        }
    }
    return findKeyByValue(map,radioGroup.getChildAt(0).getText());
}

ui.taobao.click(() => {
    threads.start(function(){
        // utils.postJs("https://code.aliyun.com/zousy201314/xinnyJs/raw/master/js/taobao.js",{
        //     mainMins:radioVal(ui.mainMins,radioMainMap),otherSecs:radioVal(ui.otherSecs,radioOtherMap),otherSize:radioVal(ui.otherSize)
        // });

        var e = engines.execScriptFile(files.cwd()+"/js/taobao.js",{path:files.cwd()+"/js"});
        setTimeout(()=>{
            //向该脚本发送事件
            e.getEngine().emit("start", {
                    mainMins:0.2,otherSecs:5,otherSize:3
                })
            }
            ,2000);

})
});

ui.watch.click(() => {
    //选中的小视频app
    var checkedApps = apps.filter(app=>app.checked).map(app=>app.id);
    if(checkedApps.length == 0){
        alert("没有选中任何APP")
        return;
    }
    threads.start(function(){
        utils.postJs("https://code.aliyun.com/zousy201314/xinnyJs/raw/master/js/watch.js",checkedApps);
    });
});
